package com.hspedu.web.json;

import com.hspedu.web.json.entity.Dog;
import com.hspedu.web.json.entity.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

//@Controller
@RestController
public class JsonHandler {
    /**
     * 目标方法@ResponseBody//表示返回的数据是Json格式
     * 底层根据@ResponseBody返回指定格式，根据http请求
     *
     * @return
     */
    @RequestMapping("/json/dog")
    //@ResponseBody//表示返回的数据是Json格式
    public Dog getJson() {
        Dog dog = new Dog();
        dog.setName("大黄狗");
        dog.setAddress("小新的家");
        return dog;
    }

    /**
     * 指定@RequestBody，springmvc就会将
     * @param user
     * @return
     */
    @RequestMapping("/save2")
    //@ResponseBody
    public User getUSer(@RequestBody User user) {
        System.out.println("user!="+user);
        return user;
    }

    @RequestMapping("/json/dogs")
    //@ResponseBody//表示返回的数据是Json格式
    public List<Dog> getJsons() {
        List<Dog> dogs = new ArrayList<>();
       dogs.add(new Dog("大皇宫","小新的家"));
       dogs.add(new Dog("大皇宫1","小新1的家"));
       dogs.add(new Dog("大皇宫2","小新2的家"));
        return dogs;
    }

    @RequestMapping("/downFile")
    public ResponseEntity<byte[]> downFile(HttpSession session) throws IOException {
        //获取到下载文件的流
        InputStream resourceAsStream = session.getServletContext().getResourceAsStream("/img/1.png");
        //开辟存放文件的字节数组，可以支持二进制文件
        byte[] bytes = new byte[resourceAsStream.available()];
        resourceAsStream.read(bytes);//数据读到数组中
        HttpStatus ok = HttpStatus.OK;
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition","attachment;filename=1.png");
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes,httpHeaders,ok);
        return responseEntity;
    }
    @RequestMapping("/json/download")
    public ResponseEntity<byte[]> downloadFile(HttpSession session) throws IOException {
        InputStream resourceAsStream = session.getServletContext().getResourceAsStream("/img/2.png");
        byte[] bytes = new byte[resourceAsStream.available()];
        resourceAsStream.read(bytes);
        HttpStatus ok = HttpStatus.OK;
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition","attachement;filename=2.png");
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, ok);
        return responseEntity;
    }
}
